<?php
declare(strict_types = 1);

namespace Distributed\Server;

use Distributed\Contract\ServerInterface;
use Distributed\App;
use Swoole\Server;
use Swoole\Runtime;
use Distributed\Dispatcher\Dispatcher;
use UntilDistributed\RedisHash;


/**
 * 分布式事务服务
 * @author mg
 *
 */
class DistributedServer extends AbstractServer implements ServerInterface
{
	
	
	/**
	 * Start swoole server
	 *
	 * @return void
	 */
	public function start(): void
	{
		
		App::$server = new  Server($this->config['host'], $this->config['port'], SWOOLE_PROCESS, SWOOLE_SOCK_TCP);
		
		Runtime::enableCoroutine();
		
		App::$server->set($this->setting);
		
		App::$server->on('shutdown', [$this, 'onShutdown']);
		
		App::$server->on('start', [$this, 'onStart']);
		
		App::$server->on('WorkerStart', [$this, 'onWorkerStart']);
		
		App::$server->on('receive', [$this, 'onReceive']);
		
		App::$server->on('ManagerStart', [$this, 'onManagerStart']);
		
		App::$server->on('close', [$this, 'onClose']);
		
		App::$server->on('ManagerStop', [$this, 'onManagerStop']);
		
// 		App::$server->on('task', [$this, 'onTask']);
		
		App::$server->start();
		
	}
	
	
	/**
	 * 接收
	 */
	public function onReceive(Server $server, int $fd, int $reactorId, string $data):void
	{
		$res = Dispatcher::getInstance($server)->dealReceive($fd, $reactorId, $data);
		
		do {
			
			if (null === $res) {
				break ;
			}
			
			$this->sendMsg($fd, $res);
			
			break;
			
		} while (true);
		
		RedisHash::destory();
	}
	
	
	/**
	 * Stop server
	 *
	 * @return bool
	 */
	public function stop(): bool
	{
		
	}
}